var app = getApp()
var util = require('../../utils/util.js')
var orderModel = require("../../model/orderModel.js")
var userModel = require("../../model/userModel.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    money: 0,
    inputMoney: "",
    user: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
   this.init();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
  },
  init(){
    var that = this
    util.showLoading("加载中")
    userModel.getBalance(res => {
      wx.hideLoading()
      if (res.status == 1) {
        util.failToast(res.msg)
        return
      }
      app.data.user.balance = res.data
      that.setData({
        user: app.data.user
      })
    })
  },
  inputMoney(e) {
    var money = parseFloat(e.detail.value)
    this.setData({
      money: money
    })
  },
  pay() {
    var money = this.data.money
    if (money <= 0) {
      util.failToast("请输入充值金额")
      return;
    }
    var arr = ("" + money).split('.')
    if (arr.length > 1 && arr[1].length > 2) {
      util.failToast("金额格式错误")
      return;
    }
    var that = this
    util.showLoading("加载中")
    orderModel.createRechargeOrder(money, res => {
      wx.hideLoading()
      if (res.status == 1) {
        util.failToast(res.msg)
        return;
      }
      util.successToast("充值成功")
      var user = that.data.user
      user.money = Math.round(100 * (user.money + money)) / 100
      user.balance = Math.round(100 * (user.balance + money)) / 100
      app.data.user=user
      
      that.setData({
        money: 0,
        inputMoney: "",
        user: user
      })
    })
  }
})